package com.lx.wx.Filter;

import com.lx.bean.Courier;
import com.lx.bean.User;
import com.lx.service.CourierService;
import com.lx.util.UserUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @ClassName: WXFilter
 * @Description:
 * @Date Created in  2021-07-17 15:15
 * @Modified By:
 * @Author: 零巽
 */
@WebFilter({"/index.html"})
public class WXFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse resp = (HttpServletResponse)servletResponse;
        HttpServletRequest req = (HttpServletRequest)servletRequest;
        User user = null;
        //自动登录校验cookie
        Cookie[] cookies = req.getCookies();
        if (cookies != null && cookies.length != 0) {
            for (Cookie cookie : cookies) {
                String cookieName = cookie.getName();
                if ("userPhone".equals(cookieName)) {
                    String userPhone = cookie.getValue();
                    user = new User();
                    user.setPhone(userPhone);
                    HttpSession session = req.getSession();
                    UserUtil.setUser(session, user);
                    //检查用户类型
                    Courier courier = CourierService.findByPhone(userPhone);
                    if (courier != null) {
                        //说明是快递员
                        session.setAttribute("role", "courier");
                    } else {
                        session.setAttribute("role", "user");
                    }
                }
            }
        }
        //如果执行完没有值则校验session
        if (user == null) {
            user = UserUtil.getUser(req.getSession());
        }
        if (user != null) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            resp.sendRedirect("/login.html");
        }
    }

    @Override
    public void destroy() {

    }
}
